package com.tcm.controller.backend;

import com.tcm.common.enums.ResponseEnum;
import com.tcm.entity.Image;
import com.tcm.entity.dto.param.ImageUpdateParam;
import com.tcm.entity.dto.ImageUploadDto;
import com.tcm.entity.vo.ImageListResult;
import com.tcm.entity.resp.PageR;
import com.tcm.entity.resp.R;
import com.tcm.service.ImageService;
import com.tcm.utils.AccessTokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 图片管理控制器
 * @author Guqier
 * @version 1.0
 * @date 2023/7/6 17:17
 */
@Slf4j
@RestController
@RequestMapping("/pc/image")
public class ImageController {

    @Autowired
    private ImageService imageService;

    /**
     * 图片批量上传
     * @param request http请求对象
     * @param name 图片名称
     * @param type 图片类型
     * @param sequence 图片同层级排序
     * @param file 文件对象
     * @return 上传回执响应信息
     */
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public R uploadBatch(HttpServletRequest request,
                         @RequestParam List<String> name,
                         @RequestParam List<Integer> type,
                         @RequestParam(required = false) List<Integer> sequence,
                         @RequestParam List<MultipartFile> file){

        // 封装Dto
        List<ImageUploadDto> imgDto = new ArrayList<>();
        for (int i = 0; i < file.size(); i++) {
            ImageUploadDto imageUploadDto = new ImageUploadDto();
            imageUploadDto.setName(name.get(i));
            imageUploadDto.setType(type.get(i));
            imageUploadDto.setSequence(i < sequence.size() ? sequence.get(i) : 1);
            imageUploadDto.setFile(file.get(i));
            imgDto.add(imageUploadDto);
        }
        System.out.println(imgDto);
        List<Image> upload = imageService.uploadBatch(imgDto, AccessTokenUtil.getUserId(request));
        return R.success(upload);
    }

    /**
     * 分页获取图片列表
     * @param page 当前页码
     * @param pageSize 页面大小
     * @param type 图片类型，0头像，1配图
     * @param name 图片查询名称
     * @param imageIds 可选，指定图片ID提到最前
     * @return 响应结果
     */
    @RequestMapping(method = RequestMethod.GET)
    public R getImageInfoByPage(Integer page, Integer pageSize, Integer type, String name, @RequestParam(value = "imageIds", required = false) List<Long> imageIds){
        PageR<ImageListResult> imageListByPage = imageService.getImageListByPage(page, pageSize, type, name, imageIds);
        return R.success(imageListByPage);
    }

    /**
     * 修改图片信息
     * @param imageInfo 图片更新数据封装类
     * @param request http请求对象
     * @return 响应结果
     */
    @RequestMapping(method = RequestMethod.PUT)
    public R updateImageInfo(@RequestBody ImageUpdateParam imageInfo, HttpServletRequest request){
        boolean res = false;
        try {
            res = imageService.modifyImageInfo(imageInfo, AccessTokenUtil.getUserId(request));
        } catch (Exception e) {
            return R.fail(101, e.getMessage());
        }
        return res ? R.success() : R.fail(ResponseEnum.DATABASE_OPERATION_FAIL);
    }

    /**
     * 删除图片信息
     * @param ids 图片ID集合
     * @param request http请求对象
     * @return 删除结果
     */
    @RequestMapping(method = RequestMethod.DELETE)
    public R removeImage(@RequestParam("ids") List<Long> ids, HttpServletRequest request){
        // 判断参数是否为空
        if (ids.isEmpty()) {
            return R.fail(ResponseEnum.PARAM_IS_BLANK);
        }
        boolean res = false;
        try {
            res = imageService.removeImage(ids, AccessTokenUtil.getUserId(request));
        } catch (Exception e) {
            return R.fail(101, e.getMessage());
        }
        return R.success();
    }

    /**
     * 上传单个图片
     * @param name 图片名称
     * @param type 图片类型
     * @param sequence 同层级排序
     * @param file 文件
     * @param request http请求对象
     * @return 响应信息
     */
    @RequestMapping(value = "/uploadSingle", method = RequestMethod.POST)
    public R uploadSingle(@RequestParam String name,
                          @RequestParam Integer type,
                          @RequestParam(required = false) Integer sequence,
                          @RequestParam MultipartFile file, HttpServletRequest request){
        Map<String, String> map = null;
        ImageUploadDto imageUploadDto = new ImageUploadDto(name, type, sequence, file);
        try {
            map = imageService.uploadSingle(imageUploadDto, AccessTokenUtil.getUserId(request));
        } catch (Exception e) {
            return R.fail(0, e.getMessage());
        }
        return R.success(map);
    }

    /**
     * 根据图片ID列表获取Url列表
     * @param imageIds 图片ID列表
     * @return 图片url列表
     */
    @RequestMapping(value = "/url", method = RequestMethod.GET)
    public R getImageUrlsByIds(@RequestParam("imageIds") List<Long> imageIds){
        if (CollectionUtils.isEmpty(imageIds)) {
            return R.fail(ResponseEnum.PARAM_IS_BLANK);
        }
        List<ImageListResult> collect = imageService.listByIds(imageIds).stream().map(image -> {
            ImageListResult imageListResult = new ImageListResult();
            BeanUtils.copyProperties(image, imageListResult);
            return imageListResult;
        }).collect(Collectors.toList());
        return R.success(collect);
    }

}
